package u1.Server;

import u1.common.*;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NovelReadServer {
    private static ExecutorService thread = Executors.newCachedThreadPool();
    private static Socket socket;//!
    public static void startSever(int port) {
        try {
            ServerSocket readSocket = new ServerSocket(port);
            System.out.println("服务器已经启动");
            while (true) {
                socket = readSocket.accept();
                System.out.println("<<<<<<<<<<<<<<<<");
                thread.submit(new serverthread());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 线程池的使用

    public static class serverthread implements Runnable {


        public serverthread() {
        }

        @Override
        public void run() {
            String ip = socket.getInetAddress().getHostAddress();
            int socketPort = socket.getPort();
            System.out.println(ip + "\t\\" + socketPort);
            while (true) {
                Request requset = receive();
                if (constants(requset).equals("longin")) {
                    login(requset);
                } else if (constants(requset).equals("register")) {
                    register(requset);
                }
                else if (constants(requset).equals("upload")) {
                    upload(requset);
                } else if (constants(requset).equals("maxType")) {
                    maxType(requset);
                } else if (constants(requset).equals("minType")) {
                    minType(requset);
                } else if (constants(requset).equals("download")) {
                    download(requset);
                } else if (constants(requset).equals("readOnline")) {
                   readOnLine(requset);
                }
            }
        }
    }

    //确定客户端目的，返回字符串

    public static String constants(Request requset) {
        return requset.keySet().stream().findFirst().get();
    }

    // 服务器收取消息

    public static Request receive() {
        ObjectInputStream ois = null;
        OutputStream output = null;
        InputStream input = null;
        try {
            input = NovelReadServer.socket.getInputStream();
            output = NovelReadServer.socket.getOutputStream();
            ois = new ObjectInputStream(input);
            Request requset = (Request) ois.readObject();
            return requset;
        } catch (SocketException exception) {
            String ip = NovelReadServer.socket.getInetAddress().getHostAddress();
            int socketPort = NovelReadServer.socket.getPort();
            System.out.println(ip + "\t\\" + socketPort + "意外断开");
            try {
                NovelReadServer.socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        } catch (Exception e) {
            //e.printStackTrace();
            return null;
        }
    }

    // 服务器发送消息

    public static boolean send(Response response) {
        ObjectOutputStream oos = null;
        OutputStream output = null;
        InputStream input = null;
        try {
            output = socket.getOutputStream();
            input = socket.getInputStream();
            oos = new ObjectOutputStream(output);
            oos.writeObject(response);
            oos.flush();
            // oos.reset();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 登录验证

    private static boolean login(Request requset) {
        Response response;
        User user = (User) requset.get("longin");
        if (LocalUserCache.loginAccount(user)) {
            response = new Response(true, "登录成功");
            send(response);
            return true;
        } else {
            response = new Response(false, "密码错误");
            send(response);
            return false;
        }
    }

    // 注册新用户

    public static boolean register(Request requset) {
        Response response;
        User user = (User) requset.get("register");
        if (LocalUserCache.addUser(user)) {
            response = new Response(true, "注册成功");
            send(response);
            return true;
        } else {
            response = new Response(false, "用户名重复");
            response.put("register", response.getMsg());
            send(response);
            return false;
        }
    }


     // 接收客户端发来的小说
     // 保存小说返回提示

    public static Book upload(Request requset) {
        Response response;
        String str;
        Book book = (Book) requset.get("upload");
        if ((str = LocalBookCache.saveBook(book)) == null) {
            response = new Response(true, "上传成功");
            send(response);
            return book;
        } else {
            response = new Response(false, "上传失败");
            response.put("register", str);
            send(response);
            return null;
        }
    }

    // 返回需要的书籍的类型列表

    public static ArrayList<Book> minType(Request requset) {
        Response response;
        String type = (String) requset.get("minType");
        ArrayList<Book> list = LocalBookCache.getList(type);
        if (list != null) {
            response = new Response(true, "类型输入正确");
            response.put("minType", list);
            send(response);
            return list;
        } else {
            response = new Response(false, "类型输入错误");
            send(response);
            return null;
        }
    }

    // 回应客户端，返回客户端需要的书籍总类型和数量map

    public static boolean maxType(Request requset) {
        Response response;
        HashMap<String, Integer> sizeMap = (HashMap<String, Integer>) requset.get("maxType");
        sizeMap = LocalBookCache.existSize();
        if (sizeMap != null) {
            response = new Response(true, "类型列表");
            response.put("maxType", sizeMap);
            send(response);
            return true;
        } else {
            response = new Response(false, "搜索不到现在的列表");
            send(response);
            return false;
        }
    }

    //发送book类给客户端

    public static Book download(Request requset) {
        Response response;
        String str;
        Book book = (Book) requset.get("download");
        System.out.println(book);
        book = LocalBookCache.download(book);
        System.out.println(book);
        if ((book) != null) {
            response = new Response(true, "下载成功");
            response.put("download", book);
            send(response);
            return book;
        } else {
            response = new Response(false, "本地没有这本书");
            send(response);
            return null;
        }
    }


    // 在线阅读

    public static Book readOnLine(Request requset) {
        Response response;
        String str;
        String dataName = requset.getDataName();
        int page = Integer.parseInt(dataName);
        Book book = (Book) requset.get("readOnline");
        book = LocalBookCache.readOnLine(book, page);
        if ((book) != null) {
            response = new Response(true, "读取成功");
            response.put("readOnline", book);
            send(response);
            book.setContent("请下载");
            return book;
        } else {
            response = new Response(false, "到达书籍末尾，没有下一页");
            send(response);
            return null;
        }

    }

    public static void main(String[] args) {
        startSever(9090);
    }
}
